package org.linlinjava.litemall.admin.web;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.dom4j.util.StringUtils;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.admin.service.AsyncService;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.linlinjava.litemall.db.domain.LitemallNews;
import org.linlinjava.litemall.db.domain.LitemallTiXian;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Future;

@RestController
@RequestMapping("/admin/tixian")
@Validated
public class AdminTiXianController {

    @Autowired
    private LitemallTiXianService litemallTiXianService;

    @Autowired
    private LitemallUserService litemallUserService;

    @Autowired
    private LitemallMoneyLogService litemallMoneyLogService;
    @Autowired
    private AsyncService asyncService;

    @Autowired
    private LitemallBaseService  litemallBaseService;

    /**
     * username 姓名
     * tixianjin  范围
     * start  开始时间
     * end   结束时间
     *
     * @return
     */
    @RequiresPermissionsDesc(menu = {"会员管理", "提现管理"}, button = "列表")

    @GetMapping("/list/wtx")
    public Object listwtx(@RequestParam(required = false, defaultValue = "0") String username,
                          @RequestParam(required = false, defaultValue = "0") Integer tixianjin,
                          @RequestParam(required = false) String start, @RequestParam(required = false) String end,
                          @RequestParam(defaultValue = "1") Integer page,
                          @RequestParam(defaultValue = "10") Integer limit,
                          @Sort @RequestParam(defaultValue = "add_time") String sort,
                          @Order @RequestParam(defaultValue = "desc") String order) {
        return ResponseUtil.ok(litemallTiXianService.adminselectallwtx(username, tixianjin, start, end,page,limit,sort,order));
    }

    @GetMapping("/list/ytx")
    public Object listytx() {
        return ResponseUtil.ok(litemallTiXianService.adminselectallytx());
    }
    @RequiresPermissions("admin:goods:update")
    @RequiresPermissionsDesc(menu = {"会员管理", "提现管理"}, button = "同意或拒绝")


    @ResponseBody()
    @PostMapping("/shenpi")
    public Object updateRequestParam(@RequestBody LitemallTiXian litemallTiXian) {
        Subject currentUser = SecurityUtils.getSubject();
        LitemallAdmin admin = (LitemallAdmin) currentUser.getPrincipal();

        litemallTiXian.setAdminid(admin.getId());
        // 条件被驳回 提现
        if (litemallTiXian.getType() != 1) {
            int userid = litemallTiXian.getUserid();
            LitemallUser litemallUser = litemallUserService.findById(userid);

            double myjlj=litemallTiXianService.findbyid(litemallTiXian.getId()).getTixianjin();


            litemallUserService.MoneyProup(litemallUser.getId(),myjlj,6);
            litemallMoneyLogService.insertMoney(0,myjlj,"提现失败，回滚奖励金",litemallUser.getId(),"奖励金",0,litemallUser.getJianglijin()+myjlj,0);
        }else {
            /**
             * 提现成功   开始进行服务中心 奖励
             */
            LitemallUser user = litemallUserService.findById(litemallTiXian.getUserid());
            String[] userlianarr = user.getUserlian().split(",");
            Map<String, String> result = new LinkedHashMap<>();
            Map<String, String> money = new LinkedHashMap<>();
            int  sizes=1;
            int  sizex=1;
            /** 我的等级 **/
            int myleave = user.getServeCenter();
            /** 我的等级 **/
            int leave = myleave;
            //本次提现奖励金
            double myjlj=litemallTiXianService.findbyid(litemallTiXian.getId()).getTixianjin();

            ///只有本人 和 本人是 F3的情况没有任何人可以获得奖励
            if (userlianarr.length < 2 || myleave==3){
            }else {
                ///遍历 链
                for (int i =  userlianarr.length-1; i >= 0; i--) {
                    LitemallUser litemallUsersum = litemallUserService.findById(Integer.parseInt(userlianarr[i]));
                    if(litemallUsersum.getServeCenter()>leave){
                        //出现差级
                        if(!result.containsKey(litemallUsersum.getServeCenter())){
                            result.put(String.valueOf(litemallUsersum.getServeCenter()) ,String.valueOf(litemallUsersum.getId()));
                        double    myjl=myjlj * ((Double.parseDouble(litemallBaseService.selectBYnumber("FW00"+litemallUsersum.getServeCenter())) *0.01)*(litemallUsersum.getServeCenter()-leave));
                            leave=litemallUsersum.getServeCenter();
                        money.put(String.valueOf(sizes),String.valueOf(myjl));
                        sizes++;
                        }
                    }
                }

            }
            /***
             *  遍历所有级差
             */

            if( result.size()>0) {

                for (Map.Entry<String, String> entry : result.entrySet()) {
                        asyncService.getfwsmoney(Integer.parseInt(entry.getKey()),Integer.parseInt(entry.getValue()),Double.parseDouble(money.get(String.valueOf(sizex))));
                        sizex++;
                }
            }
        }

        return ResponseUtil.ok(litemallTiXianService.updatetx(litemallTiXian));
    }


    @PostMapping("/detail")
    @RequiresPermissionsDesc(menu = {"会员管理", "提现管理","提现详情"}, button = "")

    public Object userdetail(@RequestParam() Integer id) {

        return ResponseUtil.ok(litemallTiXianService.findbyid(id));
    }


}
